package cn.nuc.controller.login;

import cn.nuc.controller.warning.WaringController;
import cn.nuc.pojo.system.User;
import cn.nuc.service.system.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    public static String  url = null;
    public static HttpSession session;
    @Autowired
    private IUserService userService;
    @RequestMapping("/")
    public String startLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(Model model , String username , String password , HttpServletRequest request){
        request.getSession().setAttribute("loginMsg" , null);
        List<User> userList = userService.list(new QueryWrapper<User>().eq("username", username));
        model.addAttribute("userMsg" , null);
        model.addAttribute("pwMsg" , null);
        url = "login";
        if(userList.size() == 0){
            model.addAttribute("userMsg" , "用户名不存在");
            return "login";
        }else{
            boolean checkpw = BCrypt.checkpw(password , userList.get(0).getPassword());
            request.getSession().setAttribute("username" , username);
            session = request.getSession();
            session.setAttribute("sensor" , "无");
            if(checkpw){
//                model.addAttribute("user" , userList.get(0));
                request.getSession().setAttribute("user" , userList.get(0));
                return "home";
            }else{
                model.addAttribute("pwMsg" , "密码错误");
                return "login";
            }
        }
    }
    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("username");
        request.getSession().removeAttribute("loginMsg");
        return "/login";
    }
    @RequestMapping("/home")
    public String home(Model model , HttpServletRequest request){
        String pwdMsg = (String) request.getSession().getAttribute("pwdMsg");
        model.addAttribute("pwdMsg" , pwdMsg);
        request.getSession().removeAttribute("pwdMsg");
        return "home";
    }
}
